import { ResPage, User } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";
import qs from "qs";
import { useUserStore } from "@/stores/modules/user";

/**
 * @name 用户管理模块
 */
// 获取用户列表
export const getUserList = (params: User.ReqUserParams) => {
  if (params.createdOn != null) {
    console.log("params22");
    return http.post<ResPage<User.ResUserList>>(
      "" +
        `/pages/request!findRequests.action?requestQueryDTO.startTime=` +
        params.createdOn[0] +
        `&requestQueryDTO.endTime=` +
        params.createdOn[1],
      {},
      { params }
    );
  }
  // return http.post<ResPage<User.ResUserList>>(PORT1 + `/user/list`, params);
  return http.post<ResPage<User.ResUserList>>("" + `/pages/request!findRequests.action`, {}, { params });
};

// 获取树形用户列表
export const getUserTreeList = (params: User.ReqUserParams) => {
  console.log(params);
  params.page = params.pageNum;
  params.rows = params.pageSize;
  if (params.departmentId === "1") {
    params.departmentId = "";
  }
  // return http.post<ResPage<User.ResUserList>>(
  //   `/pages/user!find.action?userQueryDto.companyNo=1&userQueryDto.orgNo=` +
  //     params.departmentId +
  //     `&userQueryDto.lastName=` +
  //     (params.fullName == undefined ? "" : params.fullName) +
  //     `&userQueryDto.loginName=` +
  //     (params.loginName == undefined ? "" : params.loginName),
  //   {},
  //   { params }
  // );
  return http.post<ResPage<User.ResUserList>>(
    "/pages/user!find.action?userQueryDto.companyNo=1",
    qs.stringify({
      rows: params.pageSize,
      page: params.pageNum,
      sidx: "userId",
      sord: "desc",
      "userQueryDto.orgNo": params.departmentId,
      "userQueryDto.belongsGroup": "",
      "userQueryDto.roleNo": 0,
      state: "all",
      "userQueryDto.loginName": params["userQueryDto.loginName"],
      "userQueryDto.firstName": params["userQueryDto.firstName"],
      "userQueryDto.lastName": params["userQueryDto.lastName"],
      "userQueryDto.email": params["userQueryDto.email"],
      "userQueryDto.mobilePhone": params["userQueryDto.mobilePhone"],
      "userQueryDto.officePhone": params["userQueryDto.officePhone"],
      "userQueryDto.orgType": params["userQueryDto.orgType"]
    })
  );
};

// 默认角色
export const findUserDetailClient = (params: any) => {
  const randomNumber = Math.random();
  return http.post(`/pages/clientUser!findUserDetailClient.action?time=` + randomNumber, qs.stringify(params));
};

export const findCompanyClient = (params: any) => {
  return http.post(`/pages/clientCompany!findCompanyClient.action`, qs.stringify(params));
};

//用户角色
export const getRoleList = () => {
  return http.post(`/pages/role!find.action?page=1&rows=9999` + "&time=" + Date.now() + Math.random());
};
// 新增用户
export const addUser = (params: { id: string }) => {
  let newobj = {};
  let roleIdsStr = "";
  let belongsGroupIdsStr = "";
  Object.keys(params).forEach(key => {
    console.log(`${key}`);
    if (`${key}` === "userDto.roleIdsStr") {
      roleIdsStr = `${params[key]}`;
    } else if (`${key}` === "userDto.belongsGroupIdsStr") {
      belongsGroupIdsStr = `${params[key]}`;
    } else {
      newobj[`${key}`] = `${params[key]}`;
    }
  });
  // return http.post(PORT1 + `/user/add`, params);
  return http.post("/pages/user!save.action" + roleIdsStr + belongsGroupIdsStr, qs.stringify(params));
};

// 批量添加用户
export const BatchAddUser = (params: FormData) => {
  return http.post(`/user/import`, params);
};

// 编辑用户
export const editUser = (params: { id: string }) => {
  let newobj = {};
  let roleIdsStr = "";
  let belongsGroupIdsStr = "";
  Object.keys(params).forEach(key => {
    console.log(`${key}`);
    if (`${key}` === "userDto.roleIdsStr") {
      roleIdsStr = `${params[key]}`;
    } else if (`${key}` === "userDto.belongsGroupIdsStr") {
      belongsGroupIdsStr = `${params[key]}`;
    } else {
      newobj[`${key}`] = `${params[key]}`;
    }
  });
  // return http.post(PORT1 + `/user/edit`, params);
  return http.post("/pages/user!merge.action" + roleIdsStr + belongsGroupIdsStr, qs.stringify(newobj));
};

// 删除用户
export const deleteUser = (params: { id: string[] }) => {
  // return http.post(PORT1 + `/user/delete`, params);
  return http.post("/pages/user!delUser.action", qs.stringify(params));
};

// 切换用户状态
export const changeUserStatus = (params: { id: string; status: number }) => {
  return http.post(`/user/change`, params);
};

// 重置用户密码
export const resetUserPassWord = params => {
  return http.post(`/user/user!resetPassword.action`, qs.stringify(params));
};

// 导出用户数据
export const exportUserInfo = (params: User.ReqUserParams) => {
  return http.download(`/user/export`, params);
};

// 获取用户状态字典
export const getUserStatus = () => {
  return http.get<User.ResStatus[]>(`/user/status`);
};

// 获取用户性别字典
export const getUserGender = () => {
  return http.get<User.ResGender[]>(`/user/gender`);
};

// 获取用户部门树形列表
export const getUserDepartment = async () => {
  const userStore = useUserStore();
  if (userStore.departmentTree && Array.isArray(userStore.departmentTree) && userStore.departmentTree.length > 0) {
    return userStore.departmentTree;
  } else {
    const data = await http.get(`/pages/organization!findAllNew.action`, {}, { cancel: false, loading: false });
    if (data && Array.isArray(data)) {
      userStore.setDepartmentTree(data);
    }
    return data;
  }
};

// 获取用户角色字典
export const getUserRole = () => {
  return http.get<User.ResRole[]>(`/user/role`);
};
//导出用户
// export const exportUser = params => {
//   return http.post(`/pages/user!exportUser.action`, qs.stringify(params));
// };
// 导出用户数据
export const exportUser = params => {
  // let header = "userQueryDto";
  // let newobj = {};
  // if (header != null && header != "") {
  //   Object.keys(params).forEach(key => {
  //     newobj[header + "." + `${key}`] = `${params[key]}`;
  //   });
  // }
  return http.downloaditsm(
    `/pages/user!exportUser.action?userQueryDto.companyNo=1&userQueryDto.limit=46&state=all`,
    qs.stringify(params)
  );
};

// 角色赋予组
export const updateRoleByGroupId = (params: { id: string }) => {
  let newobj = {};
  let roleIdsStr = "";
  let belongsGroupIdsStr = "";
  Object.keys(params).forEach(key => {
    console.log(`${key}`);
    if (`${key}` === "userDto.roleIdsStr") {
      roleIdsStr = `${params[key]}`;
    } else if (`${key}` === "userDto.belongsGroupIdsStr") {
      belongsGroupIdsStr = `${params[key]}`;
    } else {
      newobj[`${key}`] = `${params[key]}`;
    }
  });
  // return http.post(PORT1 + `/user/edit`, params);
  return http.post("/pages/user!updateRoleByGroupId.action" + roleIdsStr + belongsGroupIdsStr, qs.stringify(newobj));
};
